package com.woniu.woniuproject.web;

import com.woniu.woniuproject.config.SendSms2;
import com.woniu.woniuproject.entity.User;
import com.woniu.woniuproject.exceptions.K15SystemException;
import com.woniu.woniuproject.service.UsersService;
import com.woniu.woniuproject.utils.Md5Utils;
import com.woniu.woniuproject.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 功能描述:<br>
 * 〈〉
 *
 * @author EDZ
 * @create 2020/11/19
 * @since 1.0.0
 */
@Controller
@Slf4j
@RequestMapping("users")
public class UsersController {

    @RequestMapping("/loggo")
    public String login(@RequestParam(value = "rdtr", defaultValue = "") String rdtr, User user, Map map,
                        HttpServletResponse response) {
        log.debug("账号:{},密码:{}", user.getUsername(), user.getPassword());
        log.debug("复选框状态:{},rdtr");
        try {
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername()+"*", user.getPassword());
                subject.login(token);
                if (rdtr != null || rdtr != "") {
                    Cookie cookie1 = new Cookie("username", user.getUsername());
                    Cookie cookie2 = new Cookie("password", user.getPassword());
                    cookie1.setMaxAge(3600 * 24 * 7);
                    cookie2.setMaxAge(3600 * 24 * 7);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                //保存用户信息
                map.put("userLogin", user);
            }
        } catch (UnknownAccountException e) {
            log.debug("账号:{}", user.getUsername() + "不存在!!!");
            map.put("errorInfo", ResponseResult.ACCOUNTNOTFOUND.getMsg());
            return "login";
        } catch (IncorrectCredentialsException e) {
            log.debug("密码:{}", user.getUsername() + "错误!!!");
            map.put("errorInfo", ResponseResult.PWDERROR.getMsg());
            return "login";
        } catch (K15SystemException e) {
            log.debug("系统错误!!!");
            map.put("errorInfo", ResponseResult.SYSTEMERROR.getMsg());
            return "login";
        }
        return "redirect:/";
    }

    //验证客户的手机号
    @Autowired
    SendSms2 sendSms;
    @RequestMapping("/userPhone")
    @ResponseBody
    public String userPhone(@RequestParam("userPhone") String userPhone, HttpServletRequest req) {
        if (userPhone == "" || userPhone == null) {
            return "3";//手机号为空
        }
        String codeP = (String) req.getSession().getAttribute("codePhone");
        if (codeP != null) {
            req.getSession().removeAttribute("codeP");
        }
        //生成验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        System.out.println(code+"-----------------");
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        //使用验证码
        Map isSend = sendSms.send(userPhone, "SMS_205820460", param);
        //设置过期时间
        if ((Boolean) isSend.get("boolean")) {
            req.getSession().setAttribute("codePhone", code);
            req.getSession().setMaxInactiveInterval(5 * 60);
            if (((String) isSend.get("message").toString().substring(12, 14)).equals("OK")) {
                return "0";//验证码发送成功
            } else {
                return "1";//验证码发送达到上限
            }
        }else {
            return "2";//验证码发送失败
        }

    }

    @Autowired
    UsersService userService;

    @PostMapping("/userRegister")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("phone") String phone,
                           @RequestParam("ConfirmPass") String ConfirmPass,
                           @RequestParam("email") String email,
                           @RequestParam("phoneStatus") String phoneStatus,
                           @RequestParam("inviteid") String inviteid,
                           Map map, HttpServletRequest req
    ) {
        if (!password.equals(ConfirmPass)) {
            log.debug("密码:{},确认密码:{}", password,ConfirmPass);
            map.put("results", "您两次填写的密码不一致请重新输入");
            return "register.html";
        }
        User user = userService.queryUserByName(username);
        if (user != null) {
            log.debug("账户重复:{}", username);
            map.put("results", "您的用户名重复请重新输入");
            return "register.html";
        }
        String codeP = (String) req.getSession().getAttribute("codePhone");
        System.out.println(codeP+"===========");
        if (codeP==null){
            log.debug("验证码错误:{}", phoneStatus);
            map.put("results", "请先获取验证码!!!!");
            return "register.html";
        }
        if (!codeP.equals(phoneStatus)){//设置手机号验证码比较
            log.debug("验证码错误:{}", phoneStatus);
            map.put("results", "您的验证码输入错误");
            return "register.html";
        }
        //密码加密认证
        String newpass = Md5Utils.getMd5Pwd("MD5", password, username, 1024);
        User ur=new User();
        ur.setUsername(username);
        ur.setPassword(newpass);
        ur.setPhone(phone);
        ur.setEmail(email);
        ur.setInviteid(inviteid);
        int rows=userService.addUser(ur);
        if (rows>0){
            log.debug("注册成功:{}", "================");
            return "login.html";  //注册成功
        }
        log.debug("注册失败:{}", phoneStatus);
        map.put("results", "注册失败请重新注册");
        return "register.html";

    }

    //找会密码
    @PostMapping("/retrievepass")
    public String retrievepass(@RequestParam("username") String username,
                              @RequestParam("phone") String phone,
                              @RequestParam("password") String password,
                              @RequestParam("ConfirmPass") String ConfirmPass,
                              @RequestParam("phoneStatus") String phoneStatus,
                              HttpServletRequest req,
                              Map map){
        String codeP = (String) req.getSession().getAttribute("codePhone");
        System.out.println(codeP+"===========");
        if (codeP==null){
            log.debug("验证码错误:{}", phoneStatus);
            map.put("results", "请先获取验证码!!!!");
            return "forget.html";
        }
        User user = userService.queryUserByName(username);
        if (user==null){
            log.debug("用户名错误:{}", username);
            map.put("results", "用户名错误,请注册后直接登录!!!!");
            return "register.html";
        }
        if (!password.equals(ConfirmPass)) {
            log.debug("密码:{},确认密码:{}", password,ConfirmPass);
            map.put("results", "您两次填写的密码不一致请重新输入");
            return "forget.html";
        }
        String newpass = Md5Utils.getMd5Pwd("MD5", password, username, 1024);
        int rows=userService.updateBypass(username,newpass);
        if (rows>0){
            return "login.html";  //密码重置成功
        }
        log.debug("密码重置失败:{}", phoneStatus);
        map.put("results", "密码重置失败请重新注册");
        return "register.html";

    }

    //通过用户名和邮箱找回密码
    @PostMapping("/emailpass")
    public String emailpass(@RequestParam("username") String username,
                            @RequestParam("ConfirmPass") String ConfirmPass,
                            @RequestParam("password") String password,
                            @RequestParam("email")String email,
                            Map map){
        User user = userService.queryUserByemail(username,email);
        if (user==null){
            log.debug("用户名或邮箱错误:{}", user);
            map.put("results", "用户名或邮箱错误,请重新输入!!!!");
            return "forget.html";
        }
        if (!password.equals(ConfirmPass)) {
            log.debug("密码:{},确认密码:{}", password,ConfirmPass);
            map.put("results", "您两次填写的密码不一致请重新输入");
            return "forget.html";
        }
        String newpass = Md5Utils.getMd5Pwd("MD5", password, username, 1024);
        int rows=userService.updateBypass(username,newpass);
        if (rows>0){
            return "login.html";  //密码重置成功
        }
        log.debug("密码重置失败:{}", password);
        map.put("results", "密码重置失败请重新注册");
        return "register.html";
    }


    }

